import React, { Component } from 'react';
import _ from 'underscore';
import cx from 'classnames';

import dispatcher from 'lib/dispatcher';

export default class Interactive extends Component {
  constructor(props, context){
    super(props, context);
    this.state = {
      cols: this.resetColumns(props),
      dateSortOrientation: -1,
      currentSort: null,
      currentSortOrientation: -1
    }; // state
  } // constructor

  componentWillReceiveProps(nextProps) {
    this.setState({
      cols: this.resetColumns(nextProps)
    });
  } // componentWillReceiveProps

  resetColumns(props) {
    return _.map(props.cols, col => _.defaults(col, {
      title: '',
      className: '',
      sortable: false
    }));
  } // resetColumns

  sortHandler(column, index) {
      column.sort.call(this, column, index);
  } // sortHandler

  selectedChangeHandler(title, { target: { checked } }) {
    dispatcher.dispatch({
      $type: 'set_selected_column',
      checked,
      title
    });
  } // selectEventsChangedHandler

  renderTableHeaderCell(title, index) {
    if (this.props.showSelectedColumns) {
      let exists = _.contains(this.props.selectedColumns, title);
      let cursor = (this.props.selectedColumns.length >= 12 && !exists) ? 'not-allowed' : 'pointer';
      return (
        <th key={ `${ title }-${ index }` } style={{ cursor }}>
          <label className="by-overflow" style={{ cursor }}>
            <input
              type="checkbox"
              checked={ exists }
              style={{ cursor }}
              disabled={ this.props.selectedColumns.length >= 12 && !exists }
              onChange={ this.selectedChangeHandler.bind(this, title) } />
            { title }
          </label>
        </th>
      );
    } else {
      return (
        <th key={ `${ title }-${ index }` }>
          { title }
        </th>
      );
    }
  } // renderTableHeaderCell

  renderTableHeader(columnNames) {
    let defaultColumn = this.state.cols[0];
    return (
      <thead>
        <tr>
          <th
            key="date"
            className="sortedth col-date"
            onClick={ this.sortHandler.bind(this, defaultColumn, 0) }>
            <span className="sortedtext">
              { defaultColumn.title }
            </span>
            <span className={ cx(defaultColumn.className, 'sorted-arrow', {
              'desc': this.state.dateSortOrientation === -1,
              'asc': this.state.dateSortOrientation === 1
            }) } />
          </th>
          {
            _.map(columnNames, this.renderTableHeaderCell, this)
          }
        </tr>
      </thead>
    );
  } // renderTableHeader

  existSubpage(column) {
    let identity = '.unique'
      , index = column.key.indexOf(identity);

    return (identity.length + index) === column.key.length;
  } // existSubpage

  subpageHandler(item) {
    if (this.props.onClick) {
      this.props.onClick(condition => {
        condition.slice_date = item[2].date;
        condition.slice_by_values = item[2].by_values;

        return condition;
      });
    }
  } // subpageHandler

  renderTableBody(data) {
    let contentRender = item => {
      if (this.state.cols[2].key.split('.')[2] === 'unique' && item[2].value && item[2].value !== '--') {
        return (
          <a
            data-tip="查看详细用户列表"
            onClick={ this.subpageHandler.bind(this, item) }
            style={{
              display: 'inline-block',
              cursor: 'pointer'
            }}>
            { item[2].value }
          </a>
        );
      } else {
        return (<div>{ item[2].value === null ? '--' : item[2].value }</div>);
      }
    };

    let { sum } = this.props;
    if (sum && sum.length) {
      let list = [];
      for (var i = 0; i < this.dimensionValues.length; i++) {
        let item = _.find(sum[0].value, p => p[1] === this.dimensionValues[i]);
        if (item) {
          list.push(item);
        }
      }
      sum[0].value = list;
    }

    return (
      <tbody>
        {
          !(sum && sum.length) ? null : _.map(sum, row => (
            <tr key="total">
              <td key="date" className="col-date">合计</td>
              {
                _.chain(row.value)
                  .filter(p => p.length > 2)
                  .map(item => (
                    <td key={ item[1] }>
                      {
                        item[2].value !== undefined ? contentRender(item) : null
                      }
                      <div className={ cx('ratio', {
                        'ratio-neg': item[2].percentValue < 0,
                        'ratio-pos': item[2].percentValue >= 0
                      })}>{ item[2].percent }</div>
                    </td>
                  ))
                  .value()
              }
            </tr>
          ))
        }
        {
          _.map(data, row => (
            <tr key={ row.key }>
              <td key="date" className="col-date">
                { row.key }
              </td>
              {
                _.chain(row.value)
                  .filter(p => p.length > 2)
                  .map((item, index) => (
                    <td key={ `${ item[1] }-${ index }` }>
                      {
                        item[2].value !== undefined ? contentRender(item) : null
                      }
                      <div className={ cx('ratio', {
                        'ratio-neg': item[2].percentValue < 0,
                        'ratio-pos': item[2].percentValue >= 0
                      })}>{ item[2].percent }</div>
                    </td>
                  ))
                  .value()
              }
            </tr>
          ))
        }
      </tbody>
    );
  } // renderTableBody

  render() {
    this.dimensionValues = this.props.data[0].value[0].length <= 2 ? [] : _.map(this.props.data[0].value, p => p[1]);
    return (
      <div style={{
        whiteSpace: 'nowrap',
        overflowX: 'auto',
        overflowY: 'hidden'
      }}>
        <table className="table table-striped event-table">
          { this.renderTableHeader(this.dimensionValues) }
          { this.renderTableBody(this.props.data) }
        </table>
      </div>
    );
  } // render
}

Interactive.defaultProps = {
  cols: [],
  data: [],
  selectedColumns: [],
  onClick: null
};
